// 接口配置
const baseUrl = process.env.VUE_APP_BASEURL || 'http://接口域名/'
const uploadPresignedUrl = '获取上传签名/get-upload-token'

export default {
  // 上传文件到 oss
  upload(file, isShare = false) {
    let _this = this;
    return _this.getUploadKey(file, isShare)
      .then((keyInfo) => {
        return _this.uploadFileByKey(file, keyInfo);
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  upload2(file, isShare = false) {
    let _this = this;
    return _this.getUploadKey(file, isShare)
      .then((keyInfo) => {
        return _this.uploadFileByKey2(file, keyInfo);
      })
      .catch((error) => {
        return Promise.reject(error);
      })
  },
  uploadFileByKey(file, keyInfo = {}) {
    return new Promise((resolve, reject) => {
      // 如果是 base64 字符串，转成 File 对象
      if (typeof file === 'string') {
        file = this.base64ToFile(file);
      }
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status == 200) {
          resolve(keyInfo);
        } else if (this.readyState === 4) {
          reject('文件上传失败！');
        }
      })
      xhr.open('PUT', keyInfo.url);
      xhr.setRequestHeader('Content-Type', keyInfo.contentType || 'application/octet-stream');
      xhr.send(file);
    })
  },
  uploadFileByKey2(file, keyInfo = {}) {
    return new Promise((resolve, reject) => {
      // 如果是 base64 字符串，转成 File 对象
      if (typeof file === 'string') {
        file = this.base64ToFile(file);
      }
      const fileName = keyInfo.fileName;
      const signInfo = keyInfo.signInfo; // JSON.parse(keyInfo.signInfo)
      // oss 上传参数
      const formData = new FormData();
      formData.append('key', signInfo.dir + fileName); // 存储在oss的文件路径
      formData.append('OSSAccessKeyId', signInfo.accessid); // accessKeyId
      formData.append('policy', signInfo.policy); // policy
      formData.append('signature', signInfo.signature); // 签名
      formData.append('callback', signInfo.callback); // callback
      formData.append('file', file);
      formData.append('success_action_status', 200); // 成功后返回的操作码
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status == 200) {
          let data = {}
          try {data = JSON.parse(this.responseText)} catch (err) {}
          resolve(data);
        } else if (this.readyState === 4) {
          reject('文件上传失败！');
        }
      })
      xhr.open('POST', keyInfo.host);
      xhr.send(formData);
    })
  },
  // 从服务端获取上传签名信息-单个
  getUploadKey(file, isShare = false) {
    const reqUrl = baseUrl + uploadPresignedUrl;
    const originalName = file.name;
    return new Promise((resolve, reject) => {
      let xhr = new XMLHttpRequest();
      xhr.addEventListener('readystatechange', function () {
        if (this.readyState === 4 && this.status == 200) {
          let data = JSON.parse(this.responseText);
          if (data.code === 0) {
            resolve(data.data);
          } else {
            reject(data.msg);
          }
        } else if (this.readyState === 4) {
          reject('获取上传签名信息失败！');
        }
      });
      xhr.open('GET', `${reqUrl}?fileName=${originalName}&isShare=${isShare}`);
      xhr.send();
    });
  },
  // base64 转换为 file 类型
  base64ToFile(base64) {
    const arr = base64.split(',')
    const mime = arr[0].match(/:(.*?);/)[1]
    const bstr = atob(arr[1])
    let n = bstr.length
    const u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    const suffix = mime.split('/')[1]
    const filename = Date.now() + '.' + suffix
    return new File([u8arr], filename, { type: mime })
  }
}
